<template>
    <el-card>
        <template #header>
            <h3>登录</h3>
        </template>
        <el-form :model="loginForm" :rules="rules" ref="ruleFormRef" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="loginForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="loginForm.password"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="login(ruleFormRef)">登录</el-button>
            </el-form-item>
        </el-form>
    </el-card>
  </template>
  
  <script setup>
  import {useUserStore} from '@/stores/user'
  const userStore = useUserStore()
  const ruleFormRef = ref(null)
  import {ref} from 'vue'
  import {useRouter} from 'vue-router'
  import {loginApi} from '@/api/login'
  const router = useRouter()
  const loginForm = ref({
    username:'',
    password:''
  })
  console.log(userStore.userInfo.name)
  const rules = ref({
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' }
    ]
  })

  const login = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const res = await loginApi(loginForm.value)
      console.log(res.data)
      if (res.code===200) {
        userStore.userInfo=res.data
        console.log(userStore.userInfo)
        router.push('/')
      }
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
} 

  </script>
  
  <style scoped ></style>
  